package org.yaukie.auth.service.impl;

import com.google.code.kaptcha.Producer;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import javax.annotation.Resource;
import javax.imageio.ImageIO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.Base64Utils;
import org.yaukie.auth.constant.AjaxResult;
import org.yaukie.auth.service.api.CaptchaHandlerService;
import org.yaukie.base.redis.RedisOrMapCache;
import org.yaukie.base.uuid.IdUtils;

@Component
public class CaptchaHandlerServiceImpl implements CaptchaHandlerService {
    private static final Logger log = LoggerFactory.getLogger(CaptchaHandlerServiceImpl.class);
    @Resource(
            name = "captchaProducer"
    )
    private Producer captchaProducer;
    @Resource(
            name = "captchaProducerMath"
    )
    private Producer captchaProducerMath;
    @Value("${yaukie.captcha.type:math}")
    private String captchaType;
    @Value("${yaukie.captcha.expired:1}")
    private String captchaExpired;
    @Autowired
    private RedisOrMapCache redisCache;

    public CaptchaHandlerServiceImpl() {
    }

    public AjaxResult getVeriCode() {
        String uuid = IdUtils.fastSimpleUUID();
        String capchaCodeKey = "captcha_codes:" + uuid;
        String code = "";
        String text = "";
        BufferedImage image = null;
        if (!this.captchaType.equalsIgnoreCase("") && !this.captchaType.equalsIgnoreCase("math")) {
            code = this.captchaProducer.createText();
            image = this.captchaProducer.createImage(code);
        } else {
            text = this.captchaProducerMath.createText();
            code = text.substring(text.lastIndexOf("@") + 1);
            image = this.captchaProducerMath.createImage(text.substring(0, text.lastIndexOf("@")));
        }

        this.redisCache.setCacheObject(capchaCodeKey, code, Integer.parseInt(this.captchaExpired), TimeUnit.MINUTES);
        ByteArrayOutputStream fbao = new ByteArrayOutputStream();
        AjaxResult ajaxResult = AjaxResult.success();

        try {
            ImageIO.write(image, "jpg", fbao);
        } catch (IOException var9) {
            return AjaxResult.error(9001, var9.getMessage());
        }

        Map dataMap = new HashMap();
        dataMap.put("uuid", uuid);
        dataMap.put("code", new String(Base64Utils.encode(fbao.toByteArray())));
        ajaxResult.put("data", dataMap);
        return ajaxResult;
    }

    public boolean verifyCode() {
        return true;
    }
}
